package com.nblog.service;

import java.util.Date;

import com.nblog.model.SysLoginRecord;
import com.nblog.plugin.ioc.annotation.JFService;
import com.nblog.utils.DateUtils;

@JFService
public class SysLoginRecordService {
	/**
	 * 获取当天最后一条登陆信息
	 */
	private SysLoginRecord getLastSysLoginRecord(Integer sysUid){
		String[] daySartAndEnd=DateUtils.getThisDaySartAndEnd();
		String sql="select * from sys_login_record where sys_uid=? and login_date between ? and ? order by login_date desc limit 0,1";
		return SysLoginRecord.dao.findFirst(sql, sysUid,daySartAndEnd[0],daySartAndEnd[1]);
	}
	/**
	 * 保存登陆信息
	 */
	public void saveSysLoginRecord(Integer sysUid, int loginStatus) {
		SysLoginRecord lastSysLoginRecord=getLastSysLoginRecord(sysUid);
		if(lastSysLoginRecord!=null){
			 SysLoginRecord sysLoginRecord=new SysLoginRecord();
			 if(loginStatus!=1){
				 sysLoginRecord.setLoginErrTimes(lastSysLoginRecord.getLoginErrTimes()+1);
			 }else{
				 sysLoginRecord.setLoginErrTimes(loginStatus==1?0:1);
			 }
			 sysLoginRecord.setLoginDate(new Date());
			 sysLoginRecord.setSysUid(sysUid);
			 sysLoginRecord.setLoginStatus(loginStatus);
			 sysLoginRecord.save();
		}else{
			 SysLoginRecord sysLoginRecord=new SysLoginRecord();
			 sysLoginRecord.setLoginDate(new Date());
			 sysLoginRecord.setSysUid(sysUid);
			 sysLoginRecord.setLoginStatus(loginStatus);
			 sysLoginRecord.setLoginErrTimes(loginStatus==1?0:1);
			 sysLoginRecord.save();
		}
	}
	/**
	 * 判断当天是否超出登陆出错次数
	 */
	public boolean hasOverLoginErrTimes(Integer sysUid){
		SysLoginRecord sysLoginRecord=getLastSysLoginRecord(sysUid);
		if(sysLoginRecord!=null&&sysLoginRecord.getLoginErrTimes()>=5){
			return true;
		}
		return false;
	}
}
